﻿package webCode{
	
	import flash.display.Shape;
	import flash.display.DisplayObject;
	
	public class Spring extends Shape{
		
		var startNode:webNode;
		var endNode:webNode;
		var color:uint;
		var thickness:Number;
		private var friction:Number;
		private var spring:Number = 0.05;
		private var springLength:Number;
		
		public function Spring(sNode:webNode, eNode:webNode, color:uint = 000000, thickness:Number = 1)
		{
			startNode=sNode;
			endNode=eNode;
			this.color = color;
			this.thickness = thickness;
			friction =0.95;
			springLength = Math.sqrt(Math.pow((endNode.y-startNode.y),2) + Math.pow((endNode.x - startNode.x),2));
			startNode.connections.push(this);
		}
		
		
		public function drawSpring():void
		{
			graphics.clear();
			graphics.beginFill(color); 
			graphics.lineStyle(thickness, color);
			graphics.moveTo(startNode.x, startNode.y);
			graphics.lineTo(endNode.x, endNode.y);
			graphics.endFill();
		}
		public function springTo():void
		{
			var dx:Number = endNode.x - startNode.x;
			var dy:Number = endNode.y - startNode.y;
			var angle:Number = Math.atan2(dy, dx);
			var targetX:Number = endNode.x - Math.cos(angle) * springLength;
			var targetY:Number = endNode.y - Math.sin(angle) * springLength;
			if(startNode.canMove==true)
			{
				startNode.vx += (targetX - startNode.x) * spring;
				startNode.vy += (targetY - startNode.y) * spring;
				startNode.vx *= friction;
				startNode.vy *= friction;
				startNode.x += startNode.vx;
				startNode.y += startNode.vy;
			}
		}
	}
}